import { useEffect, useRef } from 'react';
import { connect } from 'umi';
import styles from './index.less';
import { DatePicker, Select, Button } from 'antd';
import moment from 'moment';

import { TRAlert } from '#/components';
import { programOverview, operateLog } from '@/assets';
import { LOG_TYPE, PROGARM_STATUS } from '../../constant/enums';
import messageConstant from '../../constant/message';
import { LOG_OPERATE_TIME_PATTERN } from '../../constant';
import { OperateLogModal, ProgramOverviewModal } from '../';

const { Option } = Select;

function Header({
  tradeCenterTime,
  hasModified,
  selectedSequence,
  sequenceList,
  currentSequenceDate,
  latestOperateLog,
  showMain,
  programList,
  dispatch,
}) {
  const operateLogModalRef = useRef();
  const programOverviewRef = useRef();

  useEffect(() => init(), []);

  /**
   * 初始化
   */
  const init = () => dispatch({ type: 'rollingBatch/fetchSequence' });

  /**
   * 选择序列
   * @param {*} sequenceId
   * @param {*} option
   */
  const changeTradeSeq = async (sequenceId) => {
    // 修改提示
    if (
      hasModified &&
      (await TRAlert.show(messageConstant.LOST_MODIFY_PROGRAM_CONTENT_WARNING_MESSAGE)).index === 0
    )
      return;
    dispatch({ type: 'rollingBatch/changeCurrentSequence', payload: { sequenceId } });
  };

  /**
   * 展示操作日志
   * @returns
   */
  const lastOperateTime = () => {
    if (!latestOperateLog) return '';
    let { operateTime, operateType } = latestOperateLog;
    switch (operateType) {
      case LOG_TYPE.CREATE:
        return (
          <div className={styles.lastOperateTime}>
            <span className={styles.label}>当前方案新建时间: </span>
            <span>{moment(operateTime).format(LOG_OPERATE_TIME_PATTERN)}</span>
          </div>
        );
      case LOG_TYPE.MODIFY_CONTENT:
      case LOG_TYPE.MODIFY_UNIT:
        return (
          <div className={styles.lastOperateTime}>
            <span className={styles.label}>当前方案最后保存时间: </span>
            <span>{moment(operateTime).format(LOG_OPERATE_TIME_PATTERN)}</span>
          </div>
        );
      case LOG_TYPE.SUBMIT:
      case LOG_TYPE.TIMELY_SUBMIT:
        return (
          <div className={styles.lastOperateTime}>
            <span className={styles.label}>当前方案最后申报时间: </span>
            <span>{moment(operateTime).format(LOG_OPERATE_TIME_PATTERN)}</span>
          </div>
        );
    }
  };

  /**
   * 点击查询按钮
   * @returns
   */
  const handleSearch = async () => {
    if (
      hasModified &&
      (await TRAlert.show(messageConstant.LOST_MODIFY_PROGRAM_CONTENT_WARNING_MESSAGE)).index === 0
    )
      return;
    dispatch({ type: 'rollingBatch/handleSearchEffect' });
    alertTradeTimeLimit();
  };

  /**
   * 弹窗提示交易时间
   */
  const alertTradeTimeLimit = () => {
    if (selectedSequence && selectedSequence.tradeSequenceId) {
      let { startTimeFirst, endTimeFirst, startTimeSecond, endTimeSecond } = selectedSequence,
        format = (date) => moment(date).format('YYYY.MM.DD HH:mm');
      let tradeTimeIntervals = [
        `${format(startTimeFirst)} - ${format(endTimeFirst)}`,
        `${format(startTimeSecond)} - ${format(endTimeSecond)}`,
      ];
      TRAlert.Info(
        messageConstant.TRADE_TIME_LIMIT_MESSAGE_TEMPLATE.replace(
          new RegExp('{}', 'g'),
          tradeTimeIntervals.join('*'),
        ),
      );
    }
  };

  /**
   * 序列日期选择更改
   * @param {*} tradeDate
   */
  const tradeDatePickOnChange = (selectedDate) =>
    dispatch({ type: 'rollingBatch/fetchSequenceByDate', payload: { tradeDate: selectedDate } });

  return (
    <div className={styles.header}>
      <div className={styles.tradeSeq}>
        <DatePicker
          className={`border-radius-5 ${styles.dataPicker}`}
          allowClear={false}
          onChange={tradeDatePickOnChange}
          value={currentSequenceDate}
          format="YYYYMMDD"
        />
        <Select
          className={styles.tradeSeqSelect}
          value={selectedSequence.tradeSequenceId}
          onChange={changeTradeSeq}
        >
          {sequenceList.map(({ tradeSequenceId: id, tradeSequenceName: name }) => (
            <Option value={id} key={id}>
              {name}
            </Option>
          ))}
        </Select>
        <Button className={styles.queryBtn} type="primary" onClick={handleSearch}>
          查询
        </Button>
      </div>
      {tradeCenterTime ? (
        <div className={styles.tradeCenterTime}>
          <span className={styles.time}>{moment(tradeCenterTime).format('HH:mm:ss')}</span>
          <div className={styles.dateAndWeek}>
            <span>{moment(tradeCenterTime).format('YYYY年MM月DD日')}</span>
            <span>{moment(tradeCenterTime).format('dddd')}</span>
          </div>
        </div>
      ) : (
        ''
      )}

      <div className={styles.right}>
        {showMain ? lastOperateTime() : ''}
        {programList.filter(({ status }) => status !== PROGARM_STATUS.CREATE).length ? (
          <div
            className={styles.programOverview}
            onClick={() => programOverviewRef.current.initHandle()}
          >
            <img className={styles.icon} src={programOverview} />
            <span>待申报方案总览</span>
          </div>
        ) : (
          ''
        )}
        {programList.filter(({ status }) => status !== PROGARM_STATUS.CREATE).length ? (
          <div
            className={styles.operateLog}
            onClick={() => operateLogModalRef.current.initHandle()}
          >
            <img className={styles.icon} src={operateLog} />
            <span>操作日志</span>
          </div>
        ) : (
          ''
        )}
      </div>
      <OperateLogModal ref={operateLogModalRef} />
      <ProgramOverviewModal ref={programOverviewRef} />
    </div>
  );
}

export default connect(
  ({
    rollingBatch: {
      tradeCenterTime,
      hasModified,
      globalSequence: {
        selected: selectedSequence,
        dataList: sequenceList,
        date: currentSequenceDate,
      },
      latestOperateLog,
      showMain,
      programList,
    },
  }) => ({
    tradeCenterTime,
    hasModified,
    selectedSequence,
    sequenceList,
    currentSequenceDate,
    latestOperateLog,
    showMain,
    programList,
  }),
)(Header);
